from datetime import time
from random import random

from commonDaoApi.impl.TtzUserDao import TTZUserDao
from commonServiceApi.CommonTradeApi import ATradeApi
from utils import HttpUtils, MumberUtils


class TTZTradeImpl(ATradeApi):



    def getIndexLotteryInfo(self):
        flowName = self.getWorkflowName("获取首页数据流程")
        indexLotteryInfoUrl = f"{self.BLogin.burl.INDEX_LOTTERY_INFO_URL}{self.BLogin.userToken}"
        indexData = HttpUtils.get("获取首页开奖数据", indexLotteryInfoUrl)
        self.BLogin.doingData = indexData["Data"]["DoingLuckList"]
        self.BLogin.doneData = indexData["Data"]["DoneLuckList"]

        # 是否有5期正在开奖中,
        return len(self.BLogin.doingData) < 5

    def getDoingLotteryInfo(self):
        flowName = self.getWorkflowName("获取当前期号流程")
        print(f"{flowName}")
        doingLotteryInfoUrl = f"{self.BLogin.burl.CURRENT_LOTTERY_INFO_URL}{self.BLogin.userToken}"
        doingLotteryInfoData = HttpUtils.get(flowName, doingLotteryInfoUrl)
        data = doingLotteryInfoData["Data"]
        print(f"当前正在开奖中的一期为{data}")
        self.BLogin.lotteryIssue = data['LotteryIssue']


    def getHistoryData(self):
        flowName = self.getWorkflowName("获取历史期号流程")
        print(f"{flowName}")
        lastTransactionUrl = f"{self.BLogin.burl.LOTTERY_HISTORY_URL}{self.BLogin.userToken}&g28=luck&Type=issue&PageNumber=1"
        historyData = HttpUtils.get(operation=flowName, url=lastTransactionUrl)
        detailData = historyData["Data"]


        self.BLogin.stop = True
        # 今日盈亏
        self.BLogin.todayWin = MumberUtils.strToInt(detailData["TodayWin"])
        # loginUserVo.setTodayWin(TodayWin)
        # if TodayWin > MumberUtils.strToInt(loginUserVo.winAmount):
        #     redis.setCurrentSnowballParentIndex(loginUserVo.phone,0)
        #     redis.setCurrentSnowballChildrenIndex(loginUserVo.phone,0)
        #     loginUserVo.setStop(False)
        #
        # if abs(TodayWin)>MumberUtils.strToInt(loginUserVo.costAmount):
        #     redis.setCurrentSnowballParentIndex(loginUserVo.phone,0)
        #     redis.setCurrentSnowballChildrenIndex(loginUserVo.phone,0)
        #     loginUserVo.setStop(False)

        dataList = detailData["List"]["Rows"][0:1]
        print(dataList)
        for index, item in enumerate(dataList):
            self.BLogin.luckNum = self.BLogin.doneData[0]["LuckNum"]
            self.BLogin.num1 = item["Num1"]
            self.BLogin.num2 = item["Num2"]
            self.BLogin.num3 = item["Num3"]
            self.BLogin.eachCostSum = item["CostSum"]
            self.BLogin.eachWinSum = item["WinSum"]
            self.BLogin.createTime = item["CreateTime"]

    def buy(self):
        flowName = self.getWorkflowName("买入流程")
        print(f"{flowName}")
        if self.BLogin.arr is None:
            print("下注字符为空")
            return
        transactionUrl = f"{self.BLogin.burl.LOTTERY_ISSUE_URL}{self.BLogin.userToken}&g28=luck&arr={self.BLogin.arr}&luckId={self.BLogin.lotteryIssue}"
        data = HttpUtils.get(operation=flowName, url=transactionUrl)
        if data == "":
            return self.BLogin

        if data["Msg"] == "参与成功":
            print("下注成功")
        print("下注完成,检查=============================")
        return  self.BLogin

    def getUserInfo(self):
            flowName = self.getWorkflowName("获取用户信息")
            print(f"{flowName}")
            userInfoUrl = f"{self.BLogin.burl.USER_INFO_URL}{self.BLogin.userToken}"
            userInfo = HttpUtils.get(operation=flowName, url = userInfoUrl)
            userInfoData = userInfo['Data']
            self.BLogin.coinBean = userInfoData["CoinBean"]
            self.BLogin.userId= userInfoData["UserId"]
            self.BLogin.nickName= userInfoData["Nickname"]

            userDao = TTZUserDao()
            userDao.updateUserInfo(self.BLogin)

    def chargeAndPay(self):
        flowName = self.getWorkflowName("抽取卡密流程")
        print(f"{flowName}")
        if not self.BLogin.exchangeIsCard :
            print(f"{self.BLogin.userPhone}设置为不交换卡片,跳过换卡片流程")
            return
        # 账号充值卡密key
        exchangeCardFlowKey= f"appId-{self.BLogin.appId}-{self.BLogin.userPhone}-exchangeCardFlow"
        if not  self.redis.hasKey(exchangeCardFlowKey) and \
            MumberUtils.strToInt(self.BLogin.currentSnowballChildrenIndex<2):
            #后续补充 微信通知

            exchangeNumUrl = f"{self.BLogin.bInfo.EXCHANGE_CARD_NUM_URL}{self.BLogin.userToken}&client=app&Type=2&Number=1&ExchangeType=1"
            flowName = self.getWorkflowName("获取抽卡次数")
            print(f"{flowName}")
            exchangeNumInfo = HttpUtils.get(operation=flowName, url=exchangeNumUrl)
            if len(exchangeNumInfo) ==0:
                return;

            exchangeNumInfoData = exchangeNumInfo['Data']
            print(f"今日换卡次数为{exchangeNumInfoData['Number']}")

            num = int(exchangeNumInfoData['Number'])
            if num == 0:
                return;

            # 系统休眠
            time.sleep(random.randint(1, 3))

            for i in range(num):
                time.sleep(random.randint(1, 3))

                """
                    滚动条流程
                """
                flowName = self.getWorkflowName("滚动-信息-流程1")
                print(f"{flowName}")
                exchangeCardUrl = f"{self.BLogin.bInfo.EXCHANGE_CARD_COMPOSE_URL}{self.BLogin.userToken}&client=app&Type=2&ExchangeType=1"
                composeData = HttpUtils.get(operation=flowName, url=exchangeCardUrl)
                number = composeData['Data']['Number']
                if number == '0':
                    print("抽取失败")
                    return

                # 获取抽取信息
                time.sleep(random.randint(1, 3))
                flowName = self.getWorkflowName("滚动-信息-流程2")
                print(f"{flowName}")
                infoUrl = f"{self.BLogin.bInfo.EXCHANGE_CARD_COMPOSE_INFO_URL}{self.BLogin.userToken}&client=app&Type=1&Num=1"
                infoData = HttpUtils.get("获取中奖信息", infoUrl)
                time.sleep(random.randint(1, 3))


                # 获取商品列表
                flowName = self.getWorkflowName("获取商品列表")
                composeListUrl = f"{self.BLogin.bInfo.EXCHANGE_CARD_COMPOSE_LIST}{self.BLogin.userToken}&client=app"
                composeListInfo = HttpUtils.get(operation="获取可合成商品列表",url= composeListUrl)
                composeListInfoLists = composeListInfo['Data']['List']
                result = [compose for compose in composeListInfoLists if compose['Name'] == '火蚁卡']

                GoodsId= result[0]['Id']
                time.sleep(random.randint(1, 3))
                composeGoodsUrl = f"{self.BLogin.bInfo.EXCHANGE_CARD_COMPOSE_GOODS}{self.BLogin.userToken}&client=app&GoodsId={GoodsId}&Number=1"
                composeGoodsInfo = HttpUtils.get("合成火蚁卡", composeGoodsUrl)
                composeGoodsInfoData = composeGoodsInfo['Data']
                time.sleep(random.randint(1, 3))
                print(f"合成成功，获得{composeGoodsInfoData['Number']}张火蚁卡")
                # 发送通知

                # send_message(loginUserVo.userNoticeList, f"用户{loginUserVo.phone}-合成成功，获得{composeGoodsInfoData['Number']}张火蚁卡")



    pass
if __name__ == '__main__':
    TTZTradeImpl().makeTrade()